//
//  LGAuthController.swift
//  微博框架
//
//  Created by ming on 16/10/11.
//  Copyright © 2016年 ming. All rights reserved.
//

import UIKit
import SVProgressHUD
class LGAuthController: UIViewController {
    lazy var webView = UIWebView()
    override func loadView() {
       
        self.view = webView
        
          }
    
    
  func back(){
        
        self.dismiss(animated: true, completion: nil)
    }
  func auto(){
    
    
    //调用javaScript
    let javaScript = "document.getElementById('userId').value='15677283050';" + " document.getElementById('passwd').value='m1579116334';"
    //自动注入
    webView.stringByEvaluatingJavaScript(from: javaScript)
    
    
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        webView.delegate = self
        self.navigationItem.leftBarButtonItem = UIBarButtonItem(title: "返回", target: self, action: #selector(back))
//        self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", target: self, action: #selector(auto)
        self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", target: self, action: #selector(auto))
 

      guard  let url = URL(string: "https://api.weibo.com/oauth2/authorize?client_id=\(appkey)&redirect_uri=\(redirect_uri)&response_type=code")
        else{
            
            return
        }
         let request = URLRequest(url: url)
       webView.loadRequest(request)
    }

    

}


//webView代理方法
extension LGAuthController:UIWebViewDelegate{
    
    func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        
        print(request.url?.absoluteURL)
        let url = request.url?.absoluteString
        
        if url?.hasPrefix(redirect_uri) == false{
            return true
        }
        let code = request.url?.query
        if code?.hasPrefix("code=") == true {
            print("授权成功")
            let cod = code?.substring(from: "code=".endIndex) ?? ""
           
          
            LGNetWorKingManager.shared.loadAccessTtoken(code: cod, completion: { (isSuccess) in
                
                //通知，切换页面
                SVProgressHUD.showSuccess(withStatus: "登录成功")
                NotificationCenter.default.post(name: NSNotification.Name(rawValue: NotificationuserloadData), object: nil)
                
            })
            
            back()
            
            
           
        
        
             return false
        }else{
            
            SVProgressHUD.showSuccess(withStatus: "登录失败")
            print("授权失败")
        }
        
        
     return false
        
    }
    func webViewDidStartLoad(_ webView: UIWebView) {
        
        SVProgressHUD.show()
    }
    
    func webViewDidFinishLoad(_ webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    
}



